package com.ews.onlineexchange.service;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.ejb.EJBException;
import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import com.ews.onlineexchange.dao.ServiceSupplierDao;
import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.model.TradeRating;

/**
 * @author ALIENWARE
 *
 */
@Named
@ConversationScoped
public class TradeRatingHome extends EntityHome<TradeRating, String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private Integer minScore = 0;
	private Integer maxScore = 10;
	private Integer defaultScore = 0;
	private String 	showText ;
	
	
	@Inject
	TradeHome tradeHome;
	
	/**
	 * 防止恶意通过修改URL对无关中介进行评价
	 */
	public void validateTrade() {
		if (!tradeHome.getInstance().getBulletin().isOver()) {
			throw new EJBException();
		}
		
		if (!tradeHome.getInstance().isWinner()) {
			throw new EJBException();
		}
	}
	private Integer formerScore = 0;//未修改之前的分值
	@Override
	public TradeRating loadInstance() {
		TradeRating instance = super.loadInstance();
		formerScore = instance.getScore();
		return instance;
	}

	@Inject
	ServiceSupplierDao supplierDao;
	@Inject
	ServiceSupplierScoreCalculator serviceSupplierScoreCaluator;
	private final static String GET_SUPPLIER_TRADERATING_COUNT = ""+
			"SELECT COUNT(tradeRating) FROM TradeRating tradeRating"+
			" WHERE tradeRating.trade.supplier.id = :supplierId ";

	private final static String GET_SUPPLIER_TRADERATING = ""+
			"SELECT tradeRating FROM TradeRating tradeRating"+
			" WHERE tradeRating.trade.supplier.id = :supplierId ";

	private final static String GET_TRADE_TRADERATING = ""+
			"SELECT count(tradeRating) FROM TradeRating tradeRating"+
			" WHERE tradeRating.trade.id = :tradeId ";
	@Override
	public String saveAndFlush() {		
		
		if(!isManaged()) {
			getInstance().setTrade(tradeHome.getInstance());
		}
		long ratecount = (long)getEntityManager().createQuery(GET_TRADE_TRADERATING).setParameter("tradeId", getInstance().getTrade().getId()).getSingleResult();
		if(ratecount == 0){
			Bulletin bulletin = getInstance().getTrade().getBulletin();
			bulletin.setDone(true);
			bulletin.setDoneTime(new Date());
			getEntityManager().merge(bulletin);
			getInstance().setRatingDate(new Date());
			ServiceSupplier  supplier = getInstance().getTrade().getSupplier();
			long count = (long)getEntityManager().createQuery(GET_SUPPLIER_TRADERATING_COUNT).setParameter("supplierId", supplier.getId()).getSingleResult();
			supplier.setOrderCount((int)count+1);
			BigDecimal evalScore = serviceSupplierScoreCaluator.calcBuyerEvalScore(supplier.getId(),new BigDecimal(getInstance().getScore()));
			supplier.setCreditScore(supplier.getCreditScore().add(evalScore));
			getEntityManager().merge(supplier);
			String result = super.saveAndFlush();
			return result;
		}else{
			FacesContext.getCurrentInstance().addMessage( "",
					new FacesMessage( FacesMessage.SEVERITY_ERROR, "您已经评价过了！", "" ) );
			return null;
		}

	}
	
	public String updateGrade() {
		ServiceSupplier  supplier = getInstance().getTrade().getSupplier();
		List<TradeRating> tradeRatings = getEntityManager().createQuery(GET_SUPPLIER_TRADERATING,TradeRating.class).setParameter("supplierId", supplier.getId()).getResultList();
		BigDecimal totalScore = new BigDecimal(0);
		for (TradeRating tradeRating : tradeRatings) {
			//将本次要修改的评分跳过
			if(tradeRating.getId().equals(getInstance().getId()))continue;
			totalScore = totalScore.add(new BigDecimal(tradeRating.getScore()));
		}
		BigDecimal updateScore = serviceSupplierScoreCaluator.updateBuyerEvalScore(supplier.getId(),new BigDecimal(formerScore),new BigDecimal(getInstance().getScore()));
		supplier.setCreditScore(supplier.getCreditScore().add(updateScore));
		getEntityManager().merge(supplier);
		getInstance().setRatingDate(new Date());
		String result = super.saveAndFlush();
		return result;
	}


	public Integer getMinScore() {
		return minScore;
	}



	public void setMinScore(Integer minScore) {
		this.minScore = minScore;
	}



	public Integer getMaxScore() {
		return maxScore;
	}



	public void setMaxScore(Integer maxScore) {
		this.maxScore = maxScore;
	}

	public Integer getFormerScore() {
		return formerScore;
	}

	public void setFormerScore(Integer formerScore) {
		this.formerScore = formerScore;
	}

	public String getShowText() {
		return showText;
	}



	public void setShowText(String showText) {
		this.showText = showText;
	}
	
	public Integer getDefaultScore() {
		return defaultScore;
	}

	public void setDefaultScore(Integer defaultScore) {
		this.defaultScore = defaultScore;
	}
	
	
}
